#############################################
#This file creates Figure 4
#############################################

###Log
my_log <- file("figure4_log.txt")

sink(my_log, append=T, type="output")
sink(my_log, append=T, type="message")

cat(readChar(rstudioapi::getSourceEditorContext()$path, # Writing currently opened R script to file
             file.info(rstudioapi::getSourceEditorContext()$path)$size))

start_time <- Sys.time()
start_time


library(rio)
library(socviz)
library(multcomp)
library(tidyverse)
library(broom)
library(margins)
library(ggstance)


########################################################
# Argument Ratings 
########################################################

######################
#Process: 
#' Load each experiment; clean it; 
#' combine; run regressions as needed
#####################


############################
#Experiment 1
############################
####Load the data
exp1 <- import("./Data/exp1_cleaned.csv")

####Clean the data as needed
#DV
exp1 <- exp1 %>%
  mutate(proarg = scales::rescale(proponents), 
         conarg = scales::rescale(opponents), 
         argdiff = scales::rescale(proponents-opponents))

#Treatment Condition
exp1 <- exp1 %>%
  mutate(treat = case_when(
    condition == "No Party Cue" ~ 1, 
    condition == "Party Cue" ~ 2, 
    condition == "Neg Process" ~ 3)) %>%
  mutate(treat = factor(treat, 
                        labels=c("No Party Cue", "Party Cue", 
                                 "Cue w/Insinuation")))

#Experiment
exp1$experiment <- "Experiment 1"
exp1$pol_exp <- "Air Traffic"
exp1$treat_policy <- NA


############################
#Experiment 2
############################

####Load the data
exp2 <- import("./Data/exp2_cleaned.csv")

####Clean the data as needed
#DV
exp2 <- exp2 %>%
  mutate(argdiff = scales::rescale(proarg-conarg), 
         proarg = scales::rescale(proarg), 
         conarg = scales::rescale(conarg))

#Treatment Condition(s)
exp2 <- exp2 %>%
  mutate(treat = case_when(
    treat_info == 1 ~ 1, 
    treat_info == 2 ~ 2, 
    treat_info == 4 ~ 3)) %>%
  mutate(treat = factor(treat, 
                        labels=c("No Party Cue", "Party Cue", 
                                 "Cue w/Insinuation")))

exp2$treat_policy <- factor(exp2$treat_policy, 
                            levels=c(0,1),
                            labels=c("Conservative Change", "Liberal Change"))


#Experiment
exp2$experiment <- "Experiment 2"
exp2$pol_exp <- NA
exp2$pol_exp[exp2$treat_policy=="Conservative Change"] <- "Tax:Conservative"
exp2$pol_exp[exp2$treat_policy=="Liberal Change" ] <- "Tax:Liberal"

############################
#Experiment 3
############################

####Load the data
exp3 <- import("./Data/exp3_cleaned.csv")

####Clean the data as needed
#restrict to partisans
exp3 <- exp3 %>%
  filter(pid_3 == "Democrat" | pid_3 == "Republican")

#DV
exp3 <- exp3 %>%
  mutate(argdiff = scales::rescale(proarg-conarg), 
         proarg = scales::rescale(proarg), 
         conarg = scales::rescale(conarg))


#Treatment Condition(s)
exp3$treat <- factor(exp3$treat_3, 
                     levels=c("No Party Cue", "Party Cue", "Party Cue w/ Group Pressure"), 
                     labels=c("No Party Cue", "Party Cue", "Cue w/Insinuation"))

exp3$treat_policy <- factor(exp3$change, 
                            levels=c("Conservative Change", "Liberal Change"))

#Experiment
exp3$experiment <- "Experiment 3"
exp3$pol_exp <- NA
exp3$pol_exp[exp3$treat_policy=="Conservative Change"] <- "Tax:Conservative"
exp3$pol_exp[exp3$treat_policy=="Liberal Change"] <- "Tax:Liberal"


############################
#Binding
############################

exp1a <- exp1 %>%
  dplyr::select(proarg, conarg, argdiff, treat, experiment, pol_exp, treat_policy) 

exp2a <- exp2 %>%
  dplyr::select(proarg, conarg, argdiff, treat, experiment, pol_exp, treat_policy) 

exp3a <- exp3 %>%
  dplyr::select(proarg, conarg, argdiff, treat, experiment, pol_exp, treat_policy) 

pooled <- rbind(exp1a, exp2a, exp3a)

pooled <- pooled %>%
  mutate(experiment = factor(experiment,
                             levels=c("Experiment 1", "Experiment 2", "Experiment 3")))

pooled <- pooled %>%
  mutate(polissue = case_when(
    experiment == "Experiment 1" ~ 1, 
    experiment == "Experiment 2" & pol_exp == "Tax:Conservative" ~ 2,  
    experiment == "Experiment 2" & pol_exp == "Tax:Liberal" ~ 3, 
    experiment == "Experiment 3" & pol_exp == "Tax:Conservative" ~ 4, 
    experiment == "Experiment 3" & pol_exp == "Tax:Liberal" ~ 5), 
    polissue = factor(polissue, 
                      levels=c(1,2,3,4,5), 
                      labels=c("Experiment 1", "Exp 2: Conservative Change", 
                               "Exp 2: Liberal Change", "Exp 3: Conservative Change", 
                               "Exp 3: Liberal Change")))

#Exporting so we can make nicer tables in STATA
export(pooled, "./Figure4/pooled_argdiff.dta")



###################
#Models
###################
#Pooled
m1 <- lm(argdiff ~ treat + polissue,  data=pooled)


#Extracting Data for Subsequent Graph
coefs1 <- tidy(m1) %>%
  filter(term == "treatParty Cue" | term == "treatCue w/Insinuation") 

coefs1$experiment <- "Pooled"
coefs1$comparison <- "Coefficient"
coefs1$term <-prefix_strip(coefs1$term, "treat")

##Getting Difference btwn Treatments Data
names(coef(m1))

lincom1 <- tidy(summary(glht(m1, linfct=c("`treatParty Cue` - `treatCue w/Insinuation` = 0")))) %>%
  mutate(term = "Cue - Cue w/Insinuation", 
         comparison = "Difference in Coef",
         experiment = "Pooled") %>%
  dplyr::select(term, experiment, comparison, estimate, std.error, statistic, adj.p.value) %>%
  rename(p.value = adj.p.value)

lincom1

##############
#Experiment 1
##############

###Model 
m2 <- lm(argdiff ~ treat, data = pooled, subset=(experiment == "Experiment 1"))


###Extracting Data
coefs2 <- tidy(m2) %>%
  filter(term == "treatParty Cue" | term == "treatCue w/Insinuation")

coefs2$experiment <- "Experiment 1"
coefs2$comparison <- "Coefficient"
coefs2$term <-prefix_strip(coefs2$term, "treat")

#difference in treatment effects
names(coef(m2))

lincom2 <- tidy(summary(glht(m2, linfct=c("`treatParty Cue` - `treatCue w/Insinuation` = 0")))) %>%
  mutate(term = "Cue - Cue w/Insinuation", 
         comparison = "Difference in Coef", 
         experiment = "Experiment 1") %>%
  dplyr::select(term, experiment, comparison, estimate, std.error, statistic, adj.p.value) %>%
  rename(p.value = adj.p.value)

lincom2


##############
#Experiment 2
##############
#Model
m3 <- lm(argdiff ~ treat + treat_policy, data = pooled, subset=(experiment == "Experiment 2"))

#Extracting Data
coefs3 <- tidy(m3) %>%
  filter(term == "treatParty Cue" | term == "treatCue w/Insinuation") 

coefs3$experiment <- "Experiment 2"
coefs3$comparison <- "Coefficient"
coefs3$term <-prefix_strip(coefs3$term, "treat")

#difference
lincom3 <- tidy(summary(glht(m3, linfct=c("`treatParty Cue` - `treatCue w/Insinuation` = 0")))) %>%
  mutate(term = "Cue - Cue w/Insinuation", 
         comparison = "Difference in Coef", 
         experiment = "Experiment 2") %>%
  dplyr::select(term, experiment, comparison, estimate, std.error, statistic, adj.p.value) %>%
  rename(p.value = adj.p.value)

lincom3

##############
#Experiment 3
##############
#model
m4 <- lm(argdiff ~ treat + treat_policy, data = pooled, subset=(experiment == "Experiment 3"))

#Exacted data
coefs4 <- tidy(m4) %>%
  filter(term == "treatParty Cue" | term == "treatCue w/Insinuation") 

coefs4$experiment <- "Experiment 3"
coefs4$comparison <- "Coefficient"
coefs4$term <-prefix_strip(coefs4$term, "treat")

#difference
lincom4 <- tidy(summary(glht(m4, linfct=c("`treatParty Cue` - `treatCue w/Insinuation` = 0")))) %>%
  mutate(term = "Cue - Cue w/Insinuation", 
         comparison = "Difference in Coef", 
         experiment = "Experiment 3") %>%
  dplyr::select(term, experiment, comparison, estimate, std.error, statistic, adj.p.value) %>%
  rename(p.value = adj.p.value)


lincom4

##############
#Binding
##############

results <- rbind(coefs1, lincom1, 
                 coefs2, lincom2, 
                 coefs3, lincom3, 
                 coefs4, lincom4)

results$sig <-  if_else(results$p.value < 0.05, "Significant p < 0.05", "Insignificant p >= 0.05")


########################################################
# Inferences
########################################################

############################
#Experiment 3
############################

####Load the data
exp3a <- import("./Data/exp3_cleaned.csv") %>%
  mutate(inferences=scales::rescale(inferences)) %>%
  filter(pid_3 == "Democrat" | pid_3 == "Republican")

#Treatment Condition(s)
exp3a$treat <- factor(exp3a$treat_3, 
                     levels=c("No Party Cue", "Party Cue", "Party Cue w/ Group Pressure"), 
                     labels=c("No Party Cue", "Party Cue", "Cue w/Insinuation"))

exp3a$treat_policy <- factor(exp3a$change, 
                            levels=c("Conservative Change", "Liberal Change"))

exp3a$stereo <- factor(exp3a$change_stereotype, 
                      levels=c("Non-Stereotypical Change", "Stereotypical Change"), 
                      labels=c("Counter-Stereotypical", "Stereotypical"))


exp3a_s <- exp3a %>%
  dplyr::select(inferences, state_growth, pers_finances, community, unemployment, poor, middleclass, 
                rich, treat, treat_policy, stereo)

export(exp3a_s, "./Figure4/inferences_data.dta")

######Model 
inf <- lm(inferences ~ treat + stereo, data = exp3a_s)

#Exacted data
inf_coefs1 <- tidy(inf) %>%
  filter(term == "treatParty Cue" | term == "treatCue w/Insinuation") 

inf_coefs1$comparison <- "Coefficient"
inf_coefs1$term <-prefix_strip(inf_coefs1$term, "treat")

#difference
inf_lincom1 <- tidy(summary(glht(inf, linfct=c("`treatParty Cue` - `treatCue w/Insinuation` = 0")))) %>%
  mutate(term = "Cue - Cue w/Insinuation", 
         comparison = "Difference in Coef") %>%
  dplyr::select(term, comparison, estimate, std.error, statistic, adj.p.value) %>%
  rename(p.value = adj.p.value)

#Bind
inf_results <- rbind(inf_coefs1, inf_lincom1)

inf_results$sig <- if_else(inf_results$p.value < 0.05, "Significant p < 0.05", "Insignificant p >= 0.05")

########################################################
# Proximity
########################################################

exp3b <- import("./Data/exp3_cleaned.csv") %>% 
  filter(pid_3 == "Democrat" | pid_3 == "Republican") %>%
  mutate(treat_3 = factor(treat_3, 
                          levels=c("No Party Cue", "Party Cue", "Party Cue w/ Group Pressure"), 
                          labels=c("No Party Cue", "Party Cue", "Cue w/Insinuation")), 
         treat_5 = factor(treat_5, 
                          levels=c("No Party Cue", "Party Cue", "Interest Groups", "Companies", "Labor Unions")), 
         change = factor(change, levels=c("Conservative Change", "Liberal Change")), 
         stereo = factor(change_stereotype,   levels=c("Non-Stereotypical Change", "Stereotypical Change"), 
                         labels=c("Counter-Stereotypical", "Stereotypical")), 
         support = scales::rescale(tax_support),
         inferences = scales::rescale(inferences), 
         own_trust01 = scales::rescale(own_trust), 
         out_trust01 = scales::rescale(out_trust), 
         prox01 = scales::rescale(prox), 
         placement01 = scales::rescale(placement), 
         pid_2 = factor(pid_2, levels=c("Republican", "Democrat"))) %>%
  dplyr::select(pid_2, treat_3, treat_5, change, stereo, ideol, 
                prox, prox01, placement, placement01)

export(exp3b, "./Figure4/prox_data.dta")

###########3 Category Treatment
####Controlling for Change

#Model
prox_m1 <- lm(prox01 ~ treat_3 + stereo, data = exp3b)

#Extracting Data for Subsequent Graph
prox_coefs1 <- tidy(lm(prox01 ~ treat_3 + stereo, data = exp3b)) %>%
  filter(term == "treat_3Party Cue" | term == "treat_3Cue w/Insinuation")%>%
  mutate(term = prefix_strip(term, "treat_3"), 
         dv = "Proximity", 
         comparison = "Coefficient", 
         experiment = "Experiment 3")

#lincom
prox_lincom1 <- tidy(summary(glht(prox_m1, linfct=
                                    c("`treat_3Party Cue` - `treat_3Cue w/Insinuation` = 0")))) %>%
  mutate(term = "Cue - Cue w/Insinuation", 
         comparison = "Difference in Coef",
         dv = "Proximity") %>%
  dplyr::select(term, dv, comparison, estimate, std.error, statistic, adj.p.value) %>%
  rename(p.value = adj.p.value) %>%
  mutate(dv = "Proximity", 
         experiment = "Experiment 3")


prox1 <- bind_rows(prox_coefs1, prox_lincom1) %>%
  mutate(sig = ifelse(p.value < 0.05, "Significant p < 0.05", "Insignificant p >= 0.05"))



########################################################
# Combined Figure
########################################################
results$dv <- "Argument Ratings"
inf_results$dv <- "Policy Inferences"
inf_results$experiment <- "Experiment 3"

combined <- bind_rows(results, inf_results, prox1) %>%
  mutate(dv = factor(dv, 
                     levels=c("Argument Ratings", 
                              "Policy Inferences", 
                              "Proximity")), 
         experiment = factor(experiment, 
                             levels=c("Pooled", 
                                      "Experiment 1", 
                                      "Experiment 2", 
                                      "Experiment 3")))

combined %>%
  ggplot(aes(x=estimate, y=term, shape=sig)) + 
  geom_pointrangeh(aes(xmin=estimate-(1.96*std.error), xmax=estimate+(1.96*std.error))) + 
  theme_bw(18) + 
  facet_grid(comparison ~ dv + experiment, scales="free_y", space="free_y", 
             labeller = label_wrap_gen(width = 15)) + 
  geom_text(data=combined, aes(label=round(estimate,2)), 
            nudge_y=0.10) + 
  theme(strip.text.y = element_text(angle=0), 
        legend.position="bottom") + 
  scale_shape_manual(values=c(1,16)) + 
  labs(x = NULL,
       y = NULL, 
       shape = "Statistically Significant?") + 
  geom_vline(xintercept=0, 
             linetype="dashed", 
             color="red") + 
  scale_x_continuous(breaks=c(0, 0.1))

ggsave("./Figure4/figure4.png", 
       height=8, width=14)


end_time <- Sys.time()
end_time

closeAllConnections()

